<template>
  <div class="permission-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>权限管理</span>
          <el-button type="primary" @click="handleAddPermission"
            >新增权限</el-button
          >
        </div>
      </template>

      <!-- 权限树 -->
      <div class="permission-tree">
        <el-tree
          ref="permissionTreeRef"
          :data="permissionTreeData"
          node-key="id"
          default-expand-all
          :expand-on-click-node="false"
          :default-checked-keys="defaultCheckedKeys"
          show-checkbox
        >
          <template #default="{ node, data }">
            <span class="tree-node-content">
              <span>{{ node.label }}</span>
              <span class="tree-node-actions">
                <el-button
                  v-if="!node.isLeaf"
                  type="text"
                  size="small"
                  @click.stop="handleAddChild(data)"
                >
                  添加子项
                </el-button>
                <el-button
                  type="text"
                  size="small"
                  @click.stop="handleEditPermission(data)"
                >
                  编辑
                </el-button>
                <el-button
                  v-if="!isSystemPermission(data.id)"
                  type="text"
                  size="small"
                  danger
                  @click.stop="handleDeletePermission(data.id)"
                >
                  删除
                </el-button>
              </span>
            </span>
          </template>
        </el-tree>
      </div>
    </el-card>

    <!-- 新增/编辑权限弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form
        ref="permissionFormRef"
        :model="permissionForm"
        :rules="permissionRules"
        label-width="80px"
      >
        <el-form-item label="权限名称" prop="name">
          <el-input
            v-model="permissionForm.name"
            placeholder="请输入权限名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="权限标识" prop="code">
          <el-input
            v-model="permissionForm.code"
            placeholder="请输入权限标识"
          ></el-input>
        </el-form-item>
        <el-form-item label="权限描述" prop="description">
          <el-input
            v-model="permissionForm.description"
            type="textarea"
            placeholder="请输入权限描述"
            :rows="3"
          ></el-input>
        </el-form-item>
        <el-form-item label="父级权限" prop="parentId">
          <el-cascader
            v-model="permissionForm.parentId"
            :options="permissionOptions"
            :props="{ checkStrictly: true }"
            placeholder="请选择父级权限"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="是否菜单" prop="isMenu">
          <el-switch v-model="permissionForm.isMenu" />
        </el-form-item>
        <el-form-item v-if="permissionForm.isMenu" label="路由路径" prop="path">
          <el-input
            v-model="permissionForm.path"
            placeholder="请输入路由路径"
          ></el-input>
        </el-form-item>
        <el-form-item v-if="permissionForm.isMenu" label="图标" prop="icon">
          <el-input
            v-model="permissionForm.icon"
            placeholder="请输入图标类名"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import type { TreeInstance } from "element-plus";

// 表格数据加载状态
const loading = ref(false);

// 弹窗相关
const dialogVisible = ref(false);
const isEdit = ref(false);
const dialogTitle = ref("新增权限");
const permissionFormRef = ref<FormInstance>();
const permissionTreeRef = ref<TreeInstance>();

// 权限表单数据
const permissionForm = reactive({
  id: "",
  name: "",
  code: "",
  description: "",
  parentId: [],
  isMenu: true,
  path: "",
  icon: "",
});

// 表单验证规则
const permissionRules = ref<FormRules>({
  name: [
    { required: true, message: "请输入权限名称", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
  ],
  code: [
    { required: true, message: "请输入权限标识", trigger: "blur" },
    { min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur" },
  ],
  description: [
    { max: 200, message: "长度不能超过 200 个字符", trigger: "blur" },
  ],
  path: [
    {
      required: true,
      message: "请输入路由路径",
      trigger: "blur",
      validator: (rule, value, callback) => {
        if (permissionForm.isMenu && !value) {
          callback(new Error("请输入路由路径"));
        } else {
          callback();
        }
      },
    },
  ],
});

// 权限树数据
const permissionTreeData = ref<any[]>([
  {
    id: 1,
    label: "首页",
    path: "/homepage",
    isMenu: true,
    children: [
      {
        id: 101,
        path: "/authority",
        isMenu: true,
        label: "权限管理",
        children: [
          {
            id: 1011,
            path: "/authority/userManage",
            isMenu: true,
            label: "用户管理",
          },
          {
            id: 1012,
            path: "/authority/role",
            isMenu: true,
            label: "角色管理",
          },
          {
            id: 1013,
            path: "/authority/permission",
            isMenu: true,
            label: "菜单管理",
          },
        ],
      },
    ],
  },
]);

// 默认选中的权限
const defaultCheckedKeys = ref<number[]>([]);

// 权限选项（用于级联选择器）
const permissionOptions = ref<any[]>([]);

// 转换权限树为级联选择器选项
const transformPermissionToOptions = (tree: any[]) => {
  return tree.map((node) => {
    const option: any = {
      value: node.id,
      label: node.name,
      children: node.children
        ? transformPermissionToOptions(node.children)
        : undefined,
    };
    return option;
  });
};

// 判断是否为系统级权限（不可删除）
const isSystemPermission = (id: number): boolean => {
  // 这里可以根据实际需求定义哪些权限是系统级的，不可删除
  const systemPermissionIds = [1, 2, 3]; // 示例：顶级权限不可删除
  return systemPermissionIds.includes(id);
};

// 新增权限
const handleAddPermission = () => {
  isEdit.value = false;
  dialogTitle.value = "新增权限";
  // 重置表单
  Object.assign(permissionForm, {
    id: "",
    name: "",
    code: "",
    description: "",
    parentId: [],
    isMenu: true,
    path: "",
    icon: "",
  });
  dialogVisible.value = true;
};

// 添加子权限
const handleAddChild = (data: any) => {
  isEdit.value = false;
  dialogTitle.value = "添加子权限";
  // 设置父级权限
  Object.assign(permissionForm, {
    id: "",
    name: "",
    code: "",
    description: "",
    parentId: [data.id],
    isMenu: true,
    path: "",
    icon: "",
  });
  dialogVisible.value = true;
};

// 编辑权限
const handleEditPermission = (data: any) => {
  isEdit.value = true;
  dialogTitle.value = "编辑权限";
  // 设置表单数据
  Object.assign(permissionForm, {
    id: data.id,
    name: data.name,
    code: data.code,
    description: data.description,
    parentId: data.parentId ? [data.parentId] : [],
    isMenu: data.isMenu,
    path: data.path || "",
    icon: data.icon || "",
  });
  dialogVisible.value = true;
};

// 删除权限
const handleDeletePermission = (id: number) => {
  ElMessageBox.confirm("确定要删除这个权限吗？", "删除确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      // 模拟删除请求
      loading.value = true;
      setTimeout(() => {
        ElMessage.success("删除成功");
        // 在实际项目中，这里应该调用API删除权限，然后重新获取权限树
      }, 500);
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

// 提交表单
const handleSubmit = async () => {
  try {
    await permissionFormRef.value?.validate();

    // 模拟提交请求
    loading.value = true;
    setTimeout(() => {
      loading.value = false;
      dialogVisible.value = false;
      ElMessage.success(isEdit.value ? "编辑成功" : "新增成功");
      // 在实际项目中，这里应该调用API保存权限，然后重新获取权限树
    }, 500);
  } catch (error) {
    console.error("表单验证失败:", error);
  }
};

// 组件挂载时初始化
onMounted(() => {
  // 转换权限树为级联选择器选项
  permissionOptions.value = transformPermissionToOptions(
    permissionTreeData.value
  );
});
</script>

<style scoped lang="less">
.permission-container {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .permission-tree {
    max-height: 600px;
    overflow-y: auto;
    padding: 20px 0;
  }

  .tree-node-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
  }

  .tree-node-actions {
    display: none;
  }

  .el-tree-node:hover .tree-node-actions {
    display: flex;
    gap: 10px;
  }
}
</style>